import { onMounted, ref, onUnmounted, markRaw } from "vue";
import * as echarts from "echarts";
import darkTheme from "@/assets/echarts-theme/dark.json";

const useChart = (container) => {
  const chartInstance = ref(null);
  // 获取原始 "dark" 主题配置
  echarts.registerTheme("dark", darkTheme);
  const initChart = () => {
    if (container.value) {
      chartInstance.value = markRaw(
        echarts.init(container.value, "dark", { locale: "ZH" })
      );
    }
  };

  const resizeChart = () => {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  };

  onMounted(() => {
    initChart();
    window.addEventListener("resize", resizeChart);
  });

  onUnmounted(() => {
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
    }
    window.removeEventListener("resize", resizeChart);
  });

  return {
    chartInstance,
  };
};

export default useChart;
